package com.sapient.service;

import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;

import com.sapient.service.parser.ResponseParser;

public class SessionController {
	
	private static final String SERVER_BASE_URL = "http://46.137.65.126/";
	private static final String START_SESSION = "startTest/";
	private static final String GET_NEXT_QUESTION ="/nextQuestion";
	private static final String POST_ANSWER_AND_GET_RESULT = "/answer/";
	
	private HttpClient httpClient;
	private String sessionToken;
	
	public SessionController(HttpClient httpClient){
		this.httpClient = httpClient;
	}
	
	public String establishNewSession(String name) throws ServiceException{
		String url = new StringBuilder(SERVER_BASE_URL).append(START_SESSION).append(name).toString();
		this.sessionToken = executeRequest(httpClient, url, ResponseParser.TOKENPARSER);
		return this.sessionToken;
	}
	
	public QuestionDTO nextQuestion() throws ServiceException{
		String url = new StringBuilder(SERVER_BASE_URL).append(this.sessionToken).append(GET_NEXT_QUESTION).toString();
		return executeRequest(httpClient, url, ResponseParser.QUESTION_PARSER);
	}
	
	public boolean postAnswerAndGetResult(int answer) throws ServiceException{
		String url = new StringBuilder(SERVER_BASE_URL).append(this.sessionToken).append(POST_ANSWER_AND_GET_RESULT).append(answer).toString();
		return executeRequest(httpClient, url, ResponseParser.RESULT_PARSER);
	}
	
	private <T> T executeRequest(HttpClient client, String url, ResponseParser parser) throws ServiceException{
		try {
			String responseString = client.execute(new HttpGet(url), new BasicResponseHandler());
			return (T)parser.parse(responseString);
		} catch (Exception e) {
			throw new ServiceException(e.getMessage(), e);
		}
	}
}
